var sourceCamera
var layerCamera
var key //标记地图点击事件
// 显示监控
const OpenVideo = (map) => {
  // 定义全局视频监控图层，方便方法调用
  sourceCamera = new ol.source.Vector({ wrapX: false })
  layerCamera = new ol.layer.Vector({
    source: sourceCamera,
    style: new ol.style.Style({
      image: new ol.style.Icon({
        anchor: [0.3, 50],
        anchorOrigin: "bottom-right",
        anchorXUnits: "fraction",
        anchorYUnits: "pixels",
        offsetOrigin: "top-right",
        // offset:[0,10],
        //图标缩放比例
        scale: 0.3,
        //透明度
        opacity: 1,
        //图标的url
        // src: "../../../src/assets/images/camera.png",
        src: "../../src/assets/images/camera.png",
      }),
    }),
  })
  // 1、初始化查询结构对象，设置查询结构包含几何信息
  var queryStruct = new Zondy.Service.QueryFeatureStruct()
  queryStruct.IncludeGeometry = true
  queryStruct.IncludeWebGraphic = true
  //2、创建一个用于查询的点形状
  var pointObj = new Zondy.Object.Point2D(114, 30)
  //设置点容差半径
  pointObj.nearDis = 10
  //指定查询规则
  var rule = new Zondy.Service.QueryFeatureRule({
    //是否将要素的可见性计算在内
    EnableDisplayCondition: false,
    //是否完全包含
    MustInside: false,
    //是否仅比较要素的外包矩形
    CompareRectOnly: false,
    //是否相交
    Intersect: true,
  })
  //3、实例化查询参数对象
  var queryParam = new Zondy.Service.QueryParameter({
    geometry: pointObj,
    resultFormat: "json",
    struct: queryStruct,
    rule: rule,
  })
  //4、实例化地图文档查询服务对象
  var queryService = new Zondy.Service.QueryDocFeature(
    queryParam,
    'guanggu',
    3, //监控在第3图层
    {
      ip: "localhost",
      port: "6163", //访问IGServer的端口号，.net版为6163，Java版为8089
    }
  )
  //执行查询操作，querySuccess为查询回调函数
  queryService.query(querySuccess, queryError)
  // 查询失败回调
  function queryError(e) {
    console.log(e)
  }

  //查询成功回调
  /* map-layer-source-feature[style,geometry] */
  function querySuccess(result) {
    //停止进度条
    //初始化Zondy.Format.PolygonJSON类
    var format = new Zondy.Format.PolygonJSON()
    //将MapGIS要素JSON反序列化为ol.Feature类型数组
    var features = format.read(result)
    sourceCamera.addFeatures(features)
    /* 将查询到的要素标注显示， */
    map.addLayer(layerCamera)
    // --------------------------------------------------------------------------
    /**
     * 实现popup的html元素
     */
    var container = document.getElementById("popup")
    var content = document.getElementById("popup-content")
    var closer = document.getElementById("popup-closer")
    const popup = new ol.Overlay({
      //要转换成overlay的HTML元素
      element: container,
      //当前窗口可见
      autoPan: true,
      //Popup放置的位置
      positioning: "bottom-center",
      //是否应该停止事件传播到地图窗口
      stopEvent: false,
      autoPanAnimation: {
        //当Popup超出地图边界时，为了Popup全部可见，地图移动的速度
        duration: 250,
      },
    })
    map.addOverlay(popup)

    //添加关闭按钮的单击事件（隐藏popup）
    closer.onclick = function () {
      //未定义popup位置
      popup.setPosition(undefined)
      //失去焦点
      closer.blur()
      return false
    }
    /**
     * 动态创建popup的具体内容
     * @param {string} title
     */
    function addFeatrueInfo(info) {
      //新增标题元素存放监控器编号
      var elementA = document.createElement("h5")
      elementA.style.background = "#2196f3"
      elementA.style.padding = "5px 10px"
      elementA.style.height = "25px"
      elementA.style.color = "#fff"
      setInnerText(elementA, info.att.title)
      // 新建的div元素添加A子节点
      content.appendChild(elementA)
      //新增标题元素存放监控器地址元素
      var elementDiv = document.createElement("div")
      elementDiv.style.border = " 1px solid rgb(189, 181, 181)"
      elementDiv.style.margin = "10px 0 0 0"
      // 为content添加div子节点;
      var elPositionName = document.createElement("span")
      elPositionName.innerText = "位置："
      //--- 位置样式---
      elPositionName.style.display = "inline-block"
      elPositionName.style.padding = "5px 10px"
      elPositionName.style.fontWeight = "700"
      var elPositionContent = document.createElement("span")
      elPositionContent.innerText = info.att.text
      elPositionContent.style.display = "inline-block"
      elPositionContent.style.padding = "5px 10px"

      elementDiv.appendChild(elPositionName)
      elementDiv.appendChild(elPositionContent)
      content.appendChild(elementDiv)
      //新增video元素，播放视频
      var elementVideo = document.createElement("video")
      // elementVideo.controls = true;
      elementVideo.style.padding = "10px 10px"
      elementVideo.style.border = " 1px solid rgb(189, 181, 181)"
      elementVideo.autoplay = true
      elementVideo.controls = true
      elementVideo.src = info.att.videoUrl
      // 为content添加img子节点
      content.appendChild(elementVideo)
    }

    /**
     * 动态设置元素文本内容（兼容）
     */
    function setInnerText(element, text) {
      if (typeof element.textContent == "string") {
        element.textContent = text
      } else {
        element.innerText = text
      }
    }
    // 为map添加点击事件监听，渲染弹出popup
    key = map.on("click", function (evt) {
      //判断当前单击处是否有要素，捕获到要素时弹出popup
      var feature = map.forEachFeatureAtPixel(
        evt.pixel,
        function (feature, layer) {
          return feature
        }
      )
      if (feature) {
        var obj = feature.values_.values_
        //示例标注点的信息对象
        var featuerInfo = {
          geo: feature,
          att: {
            //标注信息的标题内容
            title: "摄像头：" + obj.编号,
            //标注详细信息链接
            titleURL: "http://www.openlayers.org/",
            //标注内容简介
            text: obj.位置,

            //标注的图片
            videoUrl: "../../../src/assets/video/监控.mp4",
          },
        }

        //清空popup的内容容器
        content.innerHTML = ""
        //在popup中加载当前要素的具体信息
        addFeatrueInfo(featuerInfo)
        if (popup.getPosition() == undefined) {
          //设置popup的位置, 此时还未打开过popup弹窗
          var position = feature.getGeometry().getCoordinates()[0]
          popup.setPosition(position)
        } else {
          // 如果feature的为新点击的对象, 则赋予popup新的显示位置
          var position = feature.getGeometry().getCoordinates()[0]
          popup.setPosition(position)
        }
      }
    })
  }

  // 为map添加鼠标移动事件监听，当指向标注时改变鼠标光标状态
  map.on("pointermove", function (e) {
    // console.log(e.originalEvent);
    var pixel = map.getEventPixel(e.originalEvent)
    var hit = map.hasFeatureAtPixel(pixel)
    map.getTargetElement().style.cursor = hit ? "pointer" : ""
  })
}

// 关闭监控
const CloseVideo = (sourceCamera, layerCamera, key, map) => {
  sourceCamera.clear()
  map.removeLayer(layerCamera)
  map.getOverlays().clear()
  ol.Observable.unByKey(key)
}

export { OpenVideo, CloseVideo, sourceCamera, layerCamera, key }
